import sys
import os
import re
import csv
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QThread, pyqtSignal
import datetime
from myUI import Ui_MainWindow
from SearchPaper import SearchThread
from DownloadPaper import DownThread


# 主界面线程
class UIM_Version(Ui_MainWindow, QtWidgets.QWidget):
    send_args = pyqtSignal(list)

    def __init__(self):
        QtWidgets.QWidget.__init__(self)  # 因为继承关系，要对父类初始化
        self.path = os.path.abspath(os.path.dirname(__file__))
        self.have_search = 0
        self.have_down = 0
        self.need_down = 0
        self.down_over = False
        self.search_over = False

    # 绑定 按钮的信号与槽
    def setupFunction(self):
        self.SearchButton.clicked.connect(self.start_btn)
        self.PathSelectButton.clicked.connect(self.chgSavePath)
        self.OpenPathButton.clicked.connect(self.openSavePath)
        self.ExitButton.clicked.connect(self.exitBtn)
        self.HelpButton.clicked.connect(self.helpBtn)

    # 判断线程返回信息
    def emit_info(self, data):
        if data[:4] == '1001':      # 搜索完成
            self.show_info("\n--> 论文搜索完成，保存地址：{} \n".format(self.path))
            self.search_over = True
            if self.search_over and self.down_over:
                self.SearchButton.setText("开始")
        elif data[:4] == '1002':    # 停止搜索
            self.show_info("\n--> 停止搜索，已完成 {} 篇，保存地址：{}\n".format(self.have_search, self.path))
            self.progressBar.setValue(0)
        elif data[:4] == '1003':    # 已搜索篇数
            self.have_search = int(data[4:])
            self.show_info("--> 已搜索到 {} 篇".format(self.have_search))
            self.progressBar.setValue(int(self.have_search * 100 / self.getSearchInfo()[2]))
        elif data[:4] == '2001':     # 添加下载信息到队列
            paper_info = data[4:].split('|')
            paper_dic = {'doi': paper_info[0], 'title': paper_info[1]}
            self.need_down += 1
            self.downTrd.update_queue(paper_dic)
        elif data[:4] == '2002':      # 剩余待下载数量
            self.show_info("--> 剩余待下载 {} 篇".format(data[4:]))
        elif data[:4] == '2003':
            self.down_over = True
            if self.search_over and self.down_over:
                self.SearchButton.setText("开始")
            datalist = data[4:].splic('|')
            self.show_info("--> 下载完毕，成功{}篇，失败{}篇，文件保存在{}".format(
                datalist[0], datalist[1] - datalist[0], self.path + "\\files"))
        elif data[:4] == "2004":
            datalist = data[4:].splic('|')
            self.progressBar.setValue(int(datalist[0] * 100 / datalist[1]))
        elif data[:4] == "2005":
            self.SearchButton.setText("开始")
        elif data[:4] == '0000':    # 提示信息
            self.show_info(data[4:])

    # 开始按键
    def start_btn(self):
        self.have_search = 0
        self.have_down = 0
        self.need_down = 0
        self.progressBar.setValue(0)
        self.search_over = False
        self.down_over = False
        SearchInfo = self.getSearchInfo()

        if self.radioButton1.isChecked():
            self.search_only(SearchInfo)
        elif self.radioButton2.isChecked():
            self.down_only()
        elif self.radioButton3.isChecked():
            self.search_and_down(SearchInfo)

    # 仅搜索
    def search_only(self, SearchInfo):
        self.down_over = True
        if len(SearchInfo) == 5 and self.SearchButton.text() == "开始":
            self.SearchButton.setText("停止搜索")
            self.searchTrd = SearchThread(SearchInfo)           # 创建新线程
            self.searchTrd.update_date.connect(self.emit_info)  # 绑定显示文本框
            self.searchTrd.get_ui_info(self.path)               # 传入存储地址
            self.searchTrd.search_status(True)                  # 仅搜索
            self.searchTrd.start()
            self.send_args.emit(SearchInfo)
        elif self.SearchButton.text() == "停止搜索":
            self.searchTrd.stop_thread(True)
            self.SearchButton.setText("开始")
            self.show_info("\n--> 停止搜索 \n")
            self.searchTrd.exit()

    # 仅下载
    def down_only(self):
        self.search_over = True
        if self.SearchButton.text() == "开始":
            self.SearchButton.setText("停止下载")
            self.downTrd = DownThread()                         # 创建新线程
            self.downTrd.update_date.connect(self.emit_info)    # 绑定显示文本框
            self.downTrd.get_ui_info(int(self.spinBox.text()), self.path)   # 传入线程数和存储地址
            self.downTrd.down_status(True)                      # 仅下载
            self.downTrd.start()
        elif self.SearchButton.text() == "停止下载":
            self.downTrd.stop_thread(True)
            self.SearchButton.setText("开始")
            self.show_info("\n--> 停止下载 \n")

    # 下载并搜索
    def search_and_down(self, SearchInfo):
        if len(SearchInfo) == 5 and self.SearchButton.text() == "开始":
            self.SearchButton.setText("停止")
            # 搜索线程
            self.searchTrd = SearchThread(SearchInfo)           # 创建新线程
            self.searchTrd.update_date.connect(self.emit_info)  # 绑定显示文本框
            self.searchTrd.get_ui_info(self.path)               # 传入存储地址
            self.searchTrd.search_status(False)                 # 仅搜索
            self.searchTrd.start()
            self.send_args.emit(SearchInfo)

            # 下载线程
            self.downTrd = DownThread()                         # 创建新线程
            self.downTrd.update_date.connect(self.emit_info)    # 绑定显示文本框
            self.downTrd.get_ui_info(int(self.spinBox.text()), self.path)   # 传入线程数和存储地址
            self.downTrd.down_status(False)                     # 仅下载
            self.downTrd.start()
            print("111111")
        elif self.SearchButton.text() == "停止":
            self.searchTrd.stop_thread(True)
            self.downTrd.stop_thread(True)
            self.SearchButton.setText("开始")
            self.show_info("\n--> 停止 \n")

    # 获取输入信息并判断是否非法
    def getSearchInfo(self):
        searchInfo = []
        # 列表依次为 search_url, keywords, num, beg_year, ed_year
        searchLib = self.comboBox.currentIndex()
        searchInfo.append(searchLib)

        keyword = self.KeywordEdit.text()
        # if keyword == '':
        #     QMessageBox.warning(self,"提示！","请输入关键词后进行搜索！")
        #     return searchInfo
        keyword = "cancer"
        searchInfo.append(keyword)

        if self.NumEdit.text() == '':
            num = 5
        elif not self.NumEdit.text().isdigit():
            QMessageBox.warning(self, "提示！", "年份或篇数中存在非法字符！")
            return searchInfo
        else:
            num = int(self.NumEdit.text())
        searchInfo.append(num)

        if self.YearEdit.text() == '':
            beg_year = 1000
        elif not self.YearEdit.text().isdigit():
            QMessageBox.warning(self, "提示！", "年份或篇数中存在非法字符！")
            return searchInfo
        else:
            beg_year = int(self.YearEdit.text())
        searchInfo.append(beg_year)

        if self.YearEdit2.text() == '':
            ed_year = datetime.datetime.now().year
        elif not self.YearEdit2.text().isdigit():
            QMessageBox.warning(self, "提示！", "年份或篇数中存在非法字符！")
            return searchInfo
        else:
            ed_year = int(self.YearEdit2.text())
            if ed_year > datetime.datetime.now().year:
                ed_year = datetime.datetime.now().year
        searchInfo.append(ed_year)

        return searchInfo

    # 显示信息
    def show_info(self, data):
        self.ShowInfoEdit.appendPlainText(data)
        self.cursor = self.ShowInfoEdit.textCursor()
        self.ShowInfoEdit.moveCursor(self.cursor.End)   # 光标移到最后，这样就会自动显示出来
        QtWidgets.QApplication.processEvents()          # 一定加上这个功能，不然有卡顿

    # 保存路径初始化
    def initInfo(self):
        self.path = os.path.abspath(os.path.dirname(__file__))
        self.PathEdit.setText(self.path)
        self.progressBar.setValue(0)

    # 退出按键
    def exitBtn(self):
        qApp = QtWidgets.QApplication.instance()
        qApp.quit()

    # 帮助按键
    def helpBtn(self):
        QtWidgets.QMessageBox.about(None, "使用帮助",
                                    '<p style="color:red;text-align:center;">本软件开源免费，仅用于学习交流，请勿用于商业用途</p> \
                                    <p style="text-align:center;"><a href="https://github.com/sharele" rel="nofollow">本项目GitHub地址</a></p> \
                                    <p>关键词：（必选项）输入要检索的关键词，多个关键词用空格间隔开</p> \
                                    <p>年份：输入要检索论文的时间范围，默认无时间限制（1000-当前）</p> \
                                    <p>下载篇数：输入您要检索论文篇数，默认为 5 篇 </p> \
                                    <p>数据库：目前仅支持Pubmed、ScienceDirect，其他正在开发 </p> \
                                    <p>下载线程：仅支持多线程下载，为防止封IP，请谨慎使用</p> ')

    # 更改保存目录
    def chgSavePath(self):
        newPath = QFileDialog.getExistingDirectory(None, "请选择保存地址（文件夹）", self.path)
        if newPath:
            self.path = newPath
            self.show_info("--> 更改保存目录为：{} \n".format(self.path))
            self.PathEdit.setText(self.path)

    # 打开保存目录
    def openSavePath(self):
        os.system("explorer.exe %s" % self.path)





if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = UIM_Version()
    ui.setupUi(MainWindow)
    ui.initInfo()
    ui.setupFunction()
    MainWindow.show()

    sys.exit(app.exec_())
